package com.authine.cloudpivot.ext.controller;


import cn.hutool.core.map.MapUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.authine.cloudpivot.ext.facade.dubbo.CustomerFacade;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.ext.model.OpenFormTypeModel;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 *  表单打开方式接口
 */
@RestController
@RequestMapping("/api/oft")
@Slf4j
public class OpenFormTypeController extends BaseController {


    /**
     * 自定义RPC
     *
     */
    @Reference(version = CustomerFacade.VER)
    private CustomerFacade customerFacade;

    /**
     *  1.默认 新开窗口 2.右侧滑出
     * @param schemaCode
     * @param code
     * @return
     */
    @RequestMapping("/getOpenFormType")
    public ResponseResult getOpenFormType(String schemaCode,String code){

        if (log.isDebugEnabled()) {
            log.debug("进入 openFromControll");
        }

        if (StringUtils.isBlank(schemaCode) || StringUtils.isBlank(code)) {
            return ResponseResult.builder().errcode(-1l).errmsg("schemaCode,code 不能为空").build();
        }

        OpenFormTypeModel obj = customerFacade.findOpenFormTypeBySchemaCodeAndCode(schemaCode, code);

        if (obj == null || obj.getType() == null) {
            return  ResponseResult.builder().errcode(0l).data(MapUtil.builder("type",1).build()).build();
        }else{
            return ResponseResult.builder().errcode(0l).data(MapUtil.builder("type", obj.getType()).build()).build();
        }
    }


    @RequestMapping("/saveOpenFormType")
    public ResponseResult  saveOpenFormType(String schemaCode,String code,Integer type){

        if (log.isDebugEnabled()) {
            log.debug("进入 openFromControll...");
        }

        if (StringUtils.isBlank(schemaCode) || StringUtils.isBlank(code) || type == null) {
            return ResponseResult.builder().errcode(-1l).errmsg("schemaCode,code,type 不能为空").build();
        }

        if (!(type == 1 || type == 2)) {
            return ResponseResult.builder().errcode(-1l).errmsg("type 值范围错误[1,2]").build();
        }



        OpenFormTypeModel obj = new OpenFormTypeModel();
        obj.setSchemaCode(schemaCode);
        obj.setCode(code);
        obj.setType(type);
        obj.setCreatedBy(super.getUserId());
        obj.setCreatedTime(new Date());
        obj.setModifiedBy(super.getUserId());
        obj.setModifiedTime(new Date());

        boolean b = customerFacade.saveOpenFormTypeBySchemaCodeAndCode(obj);

        if (b) {
            return ResponseResult.builder().errcode(0l).build();
        }else {
            return ResponseResult.builder().errcode(-1l).build();
        }


    }

}
